<template>
  <div class="resource-category">
    <el-card class="box-card">
      <el-button size="small" @click="handleEdit({})">添加</el-button>
    </el-card>
    <el-table border :data="resourceCategories" style="width: 100%">
      <el-table-column label="编号" type="index" min-width="100px">
      </el-table-column>
      <el-table-column prop="name" label="名称" min-width="180px">
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" min-width="180px">
        <template slot-scope="scope">
          <span>{{ scope.row.createdTime | date }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" min-width="180px">
      </el-table-column>
      <el-table-column label="操作" min-width="180px">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <CreateOrEditCategory
      :dialogVisible="dialogVisible"
      :categories="categories"
      @close="dialogVisible = false"
      @submit="dialogSubmit"
    ></CreateOrEditCategory>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import CreateOrEditCategory from './createOrEditCategory.vue';

import {
  getResourceCategories,
  deleteResourceCategory,
  saveOrderUpdate,
  SaveOrderUpdateInter,
} from '@/services/recourse-category';

export default Vue.extend({
  name: 'RecourceCatergory',
  data() {
    return {
      resourceCategories: [],
      dialogVisible: false,
      categories: {},
    };
  },
  components: {
    CreateOrEditCategory,
  },
  created() {
    this.loadResourceCategories();
  },
  methods: {
    async loadResourceCategories() {
      const { data } = await getResourceCategories();
      if (data.code === '000000') {
        this.resourceCategories = data.data;
      }
    },
    async dialogSubmit(item: SaveOrderUpdateInter) {
      const { data } = await saveOrderUpdate(item);
      if (data.code === '000000') {
        this.dialogVisible = false;
        this.$message.success('操作成功');
        this.loadResourceCategories();
      }
    },
    handleEdit(item: { [key: string]: string | number }) {
      this.categories = item;
      this.dialogVisible = true;
    },
    handleDelete(item: { [key: string]: number }) {
      this.$confirm('是否要删除该分类?', '提示', {
        type: 'warning',
      }).then(async () => {
        const { data } = await deleteResourceCategory(item.id);
        if (data.code === '000000') {
          this.$message.success('删除成功');
          this.loadResourceCategories();
        }
      });
    },
  },
});
</script>

<style lang="scss" scoped></style>
